//
//  AppDelegate.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/6/23.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "AppDelegate.h"
#import "DDLoginRootVC.h"
#import "MainViewController.h"
#import "DDNetWorkAPIClient.h"
#import "UIImageView+WebCache.h"
#import "DDBanner.h"
#import "DDNetWorkAPIClient.h"
#import "XGPush.h"
#import "XGSetting.h"
#import "DDSystemVC.h"
#import "DDReplyMeVC.h"
#import "DDAdoptedVC.h"
#import "DDAskVC.h"
#import "DDPushDB.h"
#import "LK_NSDictionary2Object.h"
#import "JSONKit.h"
#import "MobClick.h"
#import "InitialShareSdk.h"

#define _IPHONE80_ 80000

@interface AppDelegate ()<WeiboSDKDelegate, WXApiDelegate, QQApiInterfaceDelegate>
@property (strong, nonatomic) UIView *lunchView;
@end

@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSLog(@"运行到-------------- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {");
    
    [MobClick startWithAppkey:@"55c785f2e0f55a5e7900379c"];/////开启友盟统计
    [MobClick setAppVersion:XcodeAppVersion];
    
    [self xgSdk:launchOptions];
    //初始化shareSDK
    [InitialShareSdk initialPlat];
    //第三方登录新浪微博
    //[WeiboSDK enableDebugMode:YES];
    //[WeiboSDK registerApp:SINA_kAppKey];
    
    //第三方登录微信
   //[WXApi registerApp:WEIXIN_AppID];
    
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    _lunchView = [[NSBundle mainBundle ]loadNibNamed:@"LaunchScreen" owner:nil options:nil][0];
    _lunchView.frame = CGRectMake(0, 0, self.window.screen.bounds.size.width, self.window.screen.bounds.size.height);
    
    
    
    
//    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
//    [network adList:@{@"positionCode":@"launch"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
//
//        [self.window addSubview:_lunchView];
//        
//        NSError *error;
//        DDBanner *banner = [[DDBanner alloc] initWithDictionary:object error:&error];
//        if (error) {
//            NSLog(@"error.userInfo=%@",error.userInfo);
//        }
//        NSArray *list = banner.data;
//        NSMutableArray *temp = [NSMutableArray array];
//        NSString *url = @"";
//        for (DDBannerCell *banner in list) {
//            [temp addObject:banner.url];
//            url = banner.url;
//        }
//        
//        UIImageView *imageV = [[UIImageView alloc] initWithFrame:self.window.frame];
//        
//        [imageV sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@""]];
//        [_lunchView addSubview:imageV];
//        
//        [self.window bringSubviewToFront:_lunchView];
//        
        //[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(removeLun) userInfo:nil repeats:NO];
    
//        
//        
//    }];
    
    [self login];
    
    UIViewController *rootViewController = [[DDLoginRootVC alloc]init];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:rootViewController];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    
    return YES;
}

/*! @brief 收到一个来自微信的请求，第三方应用程序处理完后调用sendResp向微信发送结果
 *
 * 收到一个来自微信的请求，异步处理完成后必须调用sendResp发送处理结果给微信。
 * 可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。
 * @param req 具体请求内容，是自动释放的
 */
//-(void) onReq:(BaseReq*)req
//{
//    NSLog(@"运行到---------------(void) onReq:(BaseReq*)req");
//}

/*! @brief 发送一个sendReq后，收到微信的回应
 *
 * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。
 * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。
 * @param resp具体的回应内容，是自动释放的
 */
//-(void) onResp:(BaseResp*)resp
//{
//    NSLog(@"运行到---------------(void) onResp:(BaseResp*)resp");
//    if([resp isKindOfClass:[SendAuthResp class]])
//    {
//        SendAuthResp *temp = (SendAuthResp*)resp;
//        
//        NSString *strMsg = [NSString stringWithFormat:@"code:%@,state:%@,errcode:%d", temp.code, temp.state, temp.errCode];
//        [[NSNotificationCenter defaultCenter] postNotificationName:temp.state object:strMsg];
//    }
//}

/**
 收到一个来自微博客户端程序的请求
 
 收到微博的请求后，第三方应用应该按照请求类型进行处理，处理完后必须通过 [WeiboSDK sendResponse:] 将结果回传给微博
 @param request 具体的请求对象
 */
//- (void)didReceiveWeiboRequest:(WBBaseRequest *)request;
//{
//    NSLog(@"运行到--------------- (void)didReceiveWeiboRequest:(WBBaseRequest *)request;");
//}

/**
 收到一个来自微博客户端程序的响应
 
 收到微博的响应后，第三方应用可以通过响应类型、响应的数据和 WBBaseResponse.userInfo 中的数据完成自己的功能
 @param response 具体的响应对象
 */
//- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
//{
//    NSLog(@"运行到--------------- (void)didReceiveWeiboResponse:(WBBaseResponse *)response");
//    if ([response isKindOfClass:WBAuthorizeResponse.class])
//    {
//        NSLog(@"Notifity:%@", [response.requestUserInfo objectForKey:@"NOTIFY"]);
//        [[NSNotificationCenter defaultCenter] postNotificationName:[response.requestUserInfo objectForKey:@"NOTIFY"] object:response];
//    }
//}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSLog(@"运行到--------------- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation");
    //return YES;//[WeiboSDK handleOpenURL:url delegate:self] || [TencentOAuth HandleOpenURL:url] || [WXApi handleOpenURL:url delegate:self];
    return [WeiboSDK handleOpenURL:url delegate:self] || [TencentOAuth HandleOpenURL:url] || [WXApi handleOpenURL:url delegate:self];

}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    NSLog(@"运行到---------------- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url");
    //return YES;//[WeiboSDK handleOpenURL:url delegate:self] || [TencentOAuth HandleOpenURL:url] || [WXApi handleOpenURL:url delegate:self];
    return [WeiboSDK handleOpenURL:url delegate:self] || [TencentOAuth HandleOpenURL:url] || [WXApi handleOpenURL:url delegate:self];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    NSLog(@"运行到---------------- (void)applicationWillResignActive:(UIApplication *)application");
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"运行到--------------- (void)applicationDidEnterBackground:(UIApplication *)application");
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    NSLog(@"运行到--------------- (void)applicationWillEnterForeground:(UIApplication *)application {");
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    NSLog(@"运行到----->- (void)applicationDidBecomeActive:(UIApplication *)application {");
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    //[MobClick checkUpdate];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    NSLog(@"运行到----->- (void)applicationWillTerminate:(UIApplication *)application {");
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


//-(void)removeLun
//{
//    [self login];
//}

-(void)login
{
    //登录事件
    DDSharedUser *user = [DDSharedUser shared];
    
    NSString *username = [user userDefaultValueForKey:kUsername];
    NSString *password = [user userDefaultValueForKey:kPassword];
    if (!username && !password) {
        UIViewController *rootViewController = [[DDLoginRootVC alloc]init];
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        // Override point for customization after application launch.
        self.window.backgroundColor = [UIColor whiteColor];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:rootViewController];
        self.window.rootViewController = nav;
        [self.window makeKeyAndVisible];
    }else{
        DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
        [network userAuthToken:username password:password CompletionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
            DDSharedUser *user = [DDSharedUser shared];
            
            if (isSuccess) {
                [network getUserInfo:user.access_token completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                    if (!isSuccess) {
                        UIViewController *rootViewController = [[DDLoginRootVC alloc]init];
                        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
                        // Override point for customization after application launch.
                        self.window.backgroundColor = [UIColor whiteColor];
                        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:rootViewController];
                        self.window.rootViewController = nav;
                        [self.window makeKeyAndVisible];
                    }else{
                        MainViewController *mainVC = [[MainViewController alloc] init];
                        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:mainVC];
                        nav.navigationBar.hidden = YES;
                        self.window.rootViewController = nav;
                        [self.window makeKeyAndVisible];
                    }
                    [UIView animateWithDuration:3.0 animations:^{
                        _lunchView.alpha = 0.0;
                    }completion:^(BOOL finished) {
                        [_lunchView removeFromSuperview];
                    }];
                    
                    
                }];
            }
            else {
                UIViewController *rootViewController = [[DDLoginRootVC alloc]init];
                self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
                // Override point for customization after application launch.
                self.window.backgroundColor = [UIColor whiteColor];
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:rootViewController];
                self.window.rootViewController = nav;
                [self.window makeKeyAndVisible];
            }
        }];
    }
}



#pragma mark - 信鹆



- (void)registerPushForIOS8{
    
    NSLog(@"运行到--------》 (void)registerPushForIOS8{");
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
//    
//    //Types
//    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
//    
//    //Actions
//    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
//    
//    acceptAction.identifier = @"ACCEPT_IDENTIFIER";
//    acceptAction.title = @"Accept";
//    
//    acceptAction.activationMode = UIUserNotificationActivationModeForeground;
//    acceptAction.destructive = NO;
//    acceptAction.authenticationRequired = NO;
//    
//    //Categories
//    UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
//    
//    inviteCategory.identifier = @"INVITE_CATEGORY";
//    
//    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextDefault];
//    
//    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextMinimal];
//    
//    
//    NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
//    
//    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
//    
//    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
//    
//    
//    [[UIApplication sharedApplication] registerForRemoteNotifications];
//#endif
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    
    //Types
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    
    //Actions
    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
    
    acceptAction.identifier = @"ACCEPT_IDENTIFIER";
    acceptAction.title = @"Accept";
    
    acceptAction.activationMode = UIUserNotificationActivationModeForeground;
    acceptAction.destructive = NO;
    acceptAction.authenticationRequired = NO;
    
    //Categories
    UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
    
    inviteCategory.identifier = @"INVITE_CATEGORY";
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextDefault];
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextMinimal];
    
    //[acceptAction release];
    
    NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
    
    //[inviteCategory release];
    
    
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}

- (void)registerPush{
//    [[UIApplication sharedApplication] registerForRemoteNotifications];
    NSLog(@"运行到--------》- (void)registerPush{");

    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}

-(void)xgSdk:(NSDictionary *)launchOptions
{
    
    NSLog(@"运行到--------》-(void)xgSdk:(NSDictionary *)launchOptions");
    
    if(launchOptions)
    {
        NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if(dictionary)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kPushMessage" object:self userInfo:dictionary];
            NSLog(@"Launched from push notification: %@", dictionary[@"aps"][@"alert"]);
        }
    }
    
    //[XGPush handleReceiveNotification:nil];
    //初始化app
    //[XGPush startWithAppkey:@"IN421FX97FUT"];
    
    
    //[XGPush startApp:2200138661 appKey:@"IRN7GXS8478F"];//com.dd5s.dingdang
    [XGPush startApp:2200181313 appKey:@"I6788VNKK5TX"];//dd5s.com.dingdang
    //注销之后需要再次注册前的准备
    void (^successCallback)(void) = ^(void){
        //如果变成需要注册状态
        if(![XGPush isUnRegisterStatus])
        {
            //iOS8注册push方法
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
            
            float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
            if(sysVer < 8){
                [self registerPush];
            }
            else{
                [self registerPushForIOS8];
            }
#else
            //iOS8之前注册push方法
            //注册Push服务，注册后才能收到推送
            [self registerPush];
#endif
        }
    };
    [XGPush initForReregister:successCallback];
    //[XGPush registerPush];  //注册Push服务，注册后才能收到推送
    //推送反馈(app不在前台运行时，点击推送激活时)
    //[XGPush handleLaunching:launchOptions];
    //推送反馈回调版本示例
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush]handleLaunching's successBlock");
    };
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush]handleLaunching's errorBlock");
    };
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //清除所有通知(包含本地通知)
    //[[UIApplication sharedApplication] cancelAllLocalNotifications];
    [XGPush handleLaunching:launchOptions successCallback:successBlock errorCallback:errorBlock];
    
    
    

    //[XGPush handleReceiveNotification:nil];
    
    //初始化app
    //[XGPush startWithAppkey:@"IN421FX97FUT"];
    
    //[XGPush startAppForMSDK:354 appKey:@"xg354key"];
    //[XGPush startApp:101 appKey:@"akey"];
    
    
//    [XGPush startApp:2200138661 appKey:@"IRN7GXS8478F"];
//    //[XGPush startApp:2290000353 appKey:@"key1"];
//    
//    
//    
//    //注销之后需要再次注册前的准备
//    void (^successCallback)(void) = ^(void){
//        //如果变成需要注册状态
//        if(![XGPush isUnRegisterStatus])
//        {
//            //iOS8注册push方法
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
//            
//            float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
//            if(sysVer < 8){
//                [self registerPush];
//            }
//            else{
//                [self registerPushForIOS8];
//            }
//#else
//            //iOS8之前注册push方法
//            //注册Push服务，注册后才能收到推送
//            [self registerPush];
//#endif
//        }
//    };
//    [XGPush initForReregister:successCallback];
//    
//    //[XGPush registerPush];  //注册Push服务，注册后才能收到推送
//    
//    
//    //推送反馈(app不在前台运行时，点击推送激活时)
//    //[XGPush handleLaunching:launchOptions];
//    
//    //推送反馈回调版本示例
//    void (^successBlock)(void) = ^(void){
//        //成功之后的处理
//        NSLog(@"[XGPush]handleLaunching's successBlock");
//    };
//    
//    void (^errorBlock)(void) = ^(void){
//        //失败之后的处理
//        NSLog(@"[XGPush]handleLaunching's errorBlock");
//    };
//    
//    //角标清0
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
//    
//    //清除所有通知(包含本地通知)
//    //[[UIApplication sharedApplication] cancelAllLocalNotifications];
//    
//    [XGPush handleLaunching:launchOptions successCallback:successBlock errorCallback:errorBlock];
    
    
    
    //本地推送示例
    /*
     NSDate *fireDate = [[NSDate new] dateByAddingTimeInterval:10];
     
     NSMutableDictionary *dicUserInfo = [[NSMutableDictionary alloc] init];
     [dicUserInfo setValue:@"myid" forKey:@"clockID"];
     NSDictionary *userInfo = dicUserInfo;
     
     [XGPush localNotification:fireDate alertBody:@"测试本地推送" badge:2 alertAction:@"确定" userInfo:userInfo];
     */
}
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    
    NSLog(@"运行到--------》-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{");
    //notification是发送推送时传入的字典信息
    [XGPush localNotificationAtFrontEnd:notification userInfoKey:@"clockID" userInfoValue:@"myid"];
    
    NSLog(@"推送过来的notification======%@",notification);
    //notification是发送推送时传入的字典信息
//    [XGPush localNotificationAtFrontEnd:notification userInfoKey:@"clockID" userInfoValue:@"myid"];
//
//    //删除推送列表中的这一条
//    [XGPush delLocalNotification:notification];
//    //[XGPush delLocalNotification:@"clockID" userInfoValue:@"myid"];
//
//    //清空推送列表
//    //[XGPush clearLocalNotifications];
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_

//注册UserNotification成功的回调
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    NSLog(@"运行到5：>>>>>>>> - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings");
    //用户已经允许接收以下类型的推送
    //UIUserNotificationType allowedTypes = [notificationSettings types];
    
}

//按钮点击事件回调
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler{
    
    NSLog(@"运行到6：- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler");
    
    if([identifier isEqualToString:@"ACCEPT_IDENTIFIER"]){
        NSLog(@"ACCEPT_IDENTIFIER is clicked");
    }
    
    completionHandler();
}

#endif

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"运行到：------------> - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {");
    
    
    //NSString * deviceTokenStr = [XGPush registerDevice:deviceToken];
    DDSharedUser *user = [DDSharedUser shared];
    [XGPush setAccount:user.userInfo.uid];
    NSLog(@"user.userInfo.uid====%@",user.userInfo.uid);
    
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush Demo]register successBlock");
    };
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush Demo]register errorBlock");
    };
    //注册设备
    XGSetting *setting = (XGSetting *)[XGSetting getInstance];
    [setting setChannel:@"appstore"];
    [setting setGameServer:@"巨神峰"];
    NSLog(@"deviceToken=======%@",deviceToken);
    NSString * deviceTokenStr = [XGPush registerDevice:deviceToken successCallback:successBlock errorCallback:errorBlock];
    NSLog(@"self.deviceTokenStr=====%@",self.deviceTokenStr);
    self.deviceTokenStr = deviceTokenStr;
    //如果不需要回调
    //[XGPush registerDevice:deviceToken];
    //打印获取的deviceToken的字符串
    NSLog(@"deviceTokenStr-------->%@",deviceTokenStr);
}

//如果deviceToken获取不到会进入此事件
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    
    NSString *str = [NSString stringWithFormat: @"Error: %@",err];
    
    NSLog(@"deviceToken获取不到 Error:%@",str);
    
}

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
//    NSLog(@"运行到9：- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo");
//    NSLog(@"Receive userInfo============%@", userInfo[@"aps"][@"alert"]);
//    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"kPushMessage" object:self userInfo:userInfo];
//    
//    //ViewController *receive = [ViewController alloc];
//    
//    [XGPush handleReceiveNotification:userInfo];
//    
//    //回调版本示例
//    void (^successBlock)(void) = ^(void){
//        //成功之后的处理
//        NSLog(@"[XGPush]handleReceiveNotification successBlock");
//    };
//    void (^errorBlock)(void) = ^(void){
//        //失败之后的处理
//        NSLog(@"[XGPush]handleReceiveNotification errorBlock");
//    };
//    void (^completion)(void) = ^(void){
//        //失败之后的处理
//        NSLog(@"[xg push completion]userInfo is %@",userInfo);
//    };
//    [XGPush handleReceiveNotification:userInfo successCallback:successBlock errorCallback:errorBlock completion:completion];
//    
//    
//    
//    
//    //推送反馈(app运行时)
    NSLog(@"运行到：------------> - (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo");
//    [XGPush handleReceiveNotification:userInfo];
    
    
    /**
     *
     1、被追问的扩展示例
     {"type": 1, "topicId": 25,"qid": 123,"answerId": 121,"replyId": 26}
     
     2、被采纳的
     {"type": 2, "topicId": 25,"qid": 123,"answerId": 121}
     
     3、回答我的
     {"type": 3, "topicId": 25,"qid": 123,"answerId": 121}
     
     4、系统消息
     {"type": 4}
     */

    NSDictionary *aps = [userInfo objectForKey: @"aps"];
    NSString *alert = [aps objectForKey:@"alert"];
    NSData* jsonData = [alert dataUsingEncoding:NSUTF8StringEncoding];

    NSString * string = [[NSString alloc]  initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSArray *arr = [string componentsSeparatedByString:@" "];
    DDPushDB *pushDB = [[DDPushDB alloc] init];
    pushDB=[userInfo objectByClass:[DDPushDB class]];
    pushDB.title = arr[0];
    pushDB.content = arr[1];
    pushDB.unRead = @"0";
    NSLog(@"arr[0]===%@,arr[1]===%@,pushDB===%@",arr[0],arr[1],pushDB);
    NSLog(@"pushDB.type=>%@,pushDB.topicId=>%@,pushDB.qid=>%@,pushDB.answerId=>%@,pushDB.replyId=>%@,pushDB.unRead=>%@,pushDB.title=>%@,pushDB.content=>%@",pushDB.type,pushDB.topicId,pushDB.qid,pushDB.answerId,pushDB.replyId,pushDB.unRead,pushDB.title,pushDB.content);
    
    NSLog(@"[pushDB saveToDB]===%@",[pushDB saveToDB]?@"YES":@"NO") ;
    
    if ([pushDB.type isEqualToString:@"1"])
    {//追问列表
        DDAskVC *askVC = [[DDAskVC alloc] initWithNibName:@"DDAskVC" bundle:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:askVC];
    }
    else if ([pushDB.type isEqualToString:@"2"])
    {//被采纳的
        DDAdoptedVC *adoptedVC = [[DDAdoptedVC alloc] initWithNibName:@"DDAdoptedVC" bundle:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:adoptedVC];
    }
    else if ([pushDB.type isEqualToString:@"3"])
    {//回答我的
        DDReplyMeVC *replyMeVC = [[DDReplyMeVC alloc] initWithNibName:@"DDReplyMeVC" bundle:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:replyMeVC];
    }
    else if ([pushDB.type isEqualToString:@"4"])
    {//系统消息
        DDSystemVC *systemVC = [[DDSystemVC alloc] initWithNibName:@"DDSystemVC" bundle:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:systemVC];
    }
    
    
    //回调版本示例
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush]handleReceiveNotification successBlock");
    };
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush]handleReceiveNotification errorBlock");
    };
    void (^completion)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[xg push completion] userInfo is %@",userInfo);
    };
    [XGPush handleReceiveNotification:userInfo successCallback:successBlock errorCallback:errorBlock completion:completion];
    
}
@end
